import { useAuthStore, useRecruiterStore, useSeekerStore, useUserStore } from '@/store'
import api from '@/api'

const WHITE_LIST = ['/login', '/404', '/']
export function createPermissionGuard(router) {
  router.beforeEach(async (to, from) => {
    const authStore = useAuthStore()

    // 招聘者、管理员不可访问招聘首页
    if (authStore.role === 'recruiter' || authStore.role === 'admin') {
      if (to.path === '/') {
        if (from.path === '/') {
          return { path: 'profile' }
        } else {
          return false
        }
      }
    }
    //未设置信息的跳转至设置个人信息
    if (to.path !== '/profile') {
      const role = authStore.role
      const hasName = authStore.hasName
      if (role === 'recruiter' && !hasName) {
        return { path: 'profile' }
      }
      else if (role === 'seeker' && !hasName) {
        return { path: 'profile' }
      }
    }
    const token = authStore.accessToken

    /** 没有token */
    if (!token) {
      if (WHITE_LIST.includes(to.path)) return true
      $message.error('请先登录后再操作')
      return { path: 'login', query: { ...to.query, redirect: to.path } }
    }

    // 有token的情况
    if (to.path === '/login') return { path: '/' }
    if (WHITE_LIST.includes(to.path)) return true

    const routes = router.getRoutes()
    if (routes.find((route) => route.name === to.name)) return true

    // 判断是无权限还是404
    const { data: hasMenu } = await api.validateMenuPath(to.path)
    return hasMenu
      ? { name: '403', query: { path: to.fullPath }, state: { from: 'permission-guard' } }
      : { name: '404', query: { path: to.fullPath } }
  })
}
